/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package utils.response;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Alisson
 */
public class FileResponse implements Response{

    protected static final DateFormat HTTP_DATE_FORMAT = new SimpleDateFormat(
			"EEE, dd MMM yyyy HH:mm:ss z");
    private final File file;
    private byte[] returnFile;

    FileResponse(File file) {
        this.file = file;
    }

    public String respond() 
    {

        int numOfBytes = (int) file.length();

        FileInputStream inFile = null;
        try {
            inFile = new FileInputStream(file.getPath());
        } catch (FileNotFoundException ex) {
            Logger.getLogger(FileResponse.class.getName()).log(Level.SEVERE, null, ex);
        }

        //Determina o tamanho do arquivo e constrói um vetor de bytes do
        //mesmo tamanho

        returnFile = new byte[numOfBytes];
        try {
            inFile.read(returnFile);
        } catch (IOException ex) {
            Logger.getLogger(FileResponse.class.getName()).log(Level.SEVERE, null, ex);
        }

        //Inicia a construção da mensagem  de resposta
        StringBuilder sb = new StringBuilder();
        sb.append("HTTP/1.0 200 OK\r\n");

        //Transmissão do cabeçalho da resposta HTTP.

        sb.append("Date: ").append(HTTP_DATE_FORMAT.format(new Date()))
                .append("\r\n");
        sb.append("Server: JAVASERV Trabalho de Redes")
                .append("\r\n");
        sb.append("Connection: Close").append("\r\n");

        if (file.getName().endsWith(".jpg"))
            sb.append("Content-Type: image/jpeg\r\n");
        if (file.getName().endsWith(".gif"))
            sb.append("Content-Type: image/gif\r\n");
        if (file.getName().endsWith(".png"))
            sb.append("Content-Type: image/png\r\n");
        if (file.getName().endsWith(".htm"))
            sb.append("Content-Type: text/html\r\n");
        sb.append("Content-Length: " + numOfBytes + "\r\n");
        sb.append("\r\n");

        //sb.append(new String(fileInBytes, 0, numOfBytes));
        return sb.toString();
    }

    public byte[] getReturnFile() {
        return returnFile;
    }
}
